# -*- encoding: utf-8 -*-
'''
@文件    :   sajjclick.py
@时间    :   2023/06/22
@作者  :   Thinktank
@版本 :   1.1
@简介 :   配合桌面微信小程序使用，自动搜答案，手点答题
@许可 :   
@描述    :   None
'''

# 这里放 import lib

import os
import sys
import time


def restartSys():
    print("重新载入")
    python = sys.executable
    os.execl(python, python, *sys.argv)


while 1:
    try:
        import keyboard
        from PIL import ImageGrab  # 用于保存屏幕截图
        import win32gui
        break
    except Exception as e:
        print(e)
        if "win32gui" in str(e):
            os.system(
                "pip install pywin32 -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
            )
            print("重新打开本程序完成后续安装")
            time.sleep(5)
            sys.exit()
        elif "keyboard" in str(e):
            os.system(
                "pip install keyboard -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
            )
        elif "PIL" in str(e):
            os.system(
                "pip install pillow -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
            )
        elif "chardet" in str(e):
            os.system(
                "pip install chardet -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
            )
import json
import tkinter
import io
import threading
import ctypes
from tkinter.messagebox import *
from sql import new_search
import win32gui, win32ui
from win32api import GetSystemMetrics
from baidu import baidu
from base64 import b64encode

dc = win32gui.GetDC(0)
dcObj = win32ui.CreateDCFromHandle(dc)
monitor = (0, 0, GetSystemMetrics(0), GetSystemMetrics(1))
hwnd_from_point = win32gui.WindowFromPoint((0, 0))

local_path = os.path.dirname(__file__)
sajj_handle = win32gui.FindWindow("Chrome_WidgetWin_0", "水安将军")
autoclick = os.path.exists(f"{local_path}{os.sep}appdata{os.sep}auto")
mark = os.path.exists(f"{local_path}{os.sep}appdata{os.sep}mark")

if autoclick or mark:
    auto = True
else:
    auto = False
if auto:
    print('自动模式已经开启')
    if autoclick:
        print("自动点击")
    elif mark:
        print("自动标记")
    try:
        import pyautogui
    except:
        os.system(
            "pip install pyautogui -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
        )
        print("重新打开本程序完成后续安装")
        time.sleep(5)
        sys.exit()
#获取窗口左上角和右下角坐标
# left, top, right, bottom = win32gui.GetWindowRect(handle)
# print(left, top, right, bottom)


# 准确的坐标定义
def get_window_rect(hwnd):
    try:
        f = ctypes.windll.dwmapi.DwmGetWindowAttribute
    except WindowsError:
        f = None
    if f:
        rect = ctypes.wintypes.RECT()
        DWMWA_EXTENDED_FRAME_BOUNDS = 9
        f(ctypes.wintypes.HWND(hwnd),
          ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
          ctypes.byref(rect), ctypes.sizeof(rect))
        print('窗口位置：{} {} {} {}'.format(
            rect.left, rect.top + (rect.bottom - rect.top) // 4, rect.right,
            rect.bottom))
        return rect.left, rect.top + (rect.bottom -
                                      rect.top) // 4, rect.right, rect.bottom


def screen_thread():
    # 百度识别接口配置信息
    with open(f'{local_path}{os.sep}baidu.json') as j:
        baidu_json = json.load(j)
    APP_ID = baidu_json["APP_ID"]
    if APP_ID:
        print("json导入")
        try:
            from aip import AipOcr
        except Exception as e:
            print(e)
            if "aip" in str(e):
                os.system(
                    "pip install baidu-aip -i http://pypi.douban.com/simple --trusted-host pypi.douban.com"
                )
                sys.exit()
        API_KEY = baidu_json["API_KEY"]
        SECRET_KEY = baidu_json["SECRET_KEY"]
    else:
        print("token导入")
        myBaidu = baidu(fr"{local_path}{os.sep}\appdata\token.txt")
    while True:
        # keyboard.wait(hotkey="ctrl+alt+a")
        keyboard.wait(hotkey="space")
        # print("截图")
        time.sleep(0.01)
        check = changeVar.get()
        image = ImageGrab.grab(get_window_rect(sajj_handle))
        imgBytes1 = io.BytesIO()
        imgBytes2 = io.BytesIO()
        # image = ImageGrab.grabclipboard()
        if image:
            image = image.convert('L')
            # image.save("test1.jpeg")
            # 自定义灰度界限，大于这个值为黑色，小于这个值为白色
            threshold1 = 170
            threshold2 = 160
            table1 = []
            table2 = []
            for i in range(256):
                if i < threshold1:
                    table1.append(0)
                else:
                    table1.append(1)
            for i in range(256):
                if (i < threshold2) and (i > 120):
                    table2.append(1)
                else:
                    table2.append(0)
            image1 = image.point(table1, '1')
            # print(image1.size)
            image1.save(imgBytes1, format="jpeg")
            # image1.save("test2.jpeg")
            image2 = image.point(table2, '1')
            w, h = image2.size
            image2 = image2.crop((0, 100, w, h))
            image2.save(imgBytes2, format="jpeg")
            # image2.save("test3.jpeg")
            while 1:
                try:
                    if APP_ID:
                        client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
                        # 调用百度API通用文字识别，提取图片中的内容
                        questionTxt = client.basicGeneral(imgBytes1.getvalue())
                        if auto and check:
                            answersTxt = client.general(imgBytes2.getvalue())
                        elif check:
                            answersTxt = client.basicGeneral(
                                imgBytes2.getvalue())
                        else:
                            answersTxt = {'words_result': [{'words': ''}]}
                    else:
                        questionTxt = myBaidu.get_text(
                            "general_basic",
                            b64encode(imgBytes1.getvalue()).decode("utf8"))
                        if auto and check:
                            # answersTxt = client.general(imgBytes2.getvalue())
                            answersTxt = myBaidu.get_text(
                                "general",
                                b64encode(imgBytes2.getvalue()).decode("utf8"))
                        elif check:
                            answersTxt = myBaidu.get_text(
                                "general_basic",
                                b64encode(imgBytes2.getvalue()).decode("utf8"))
                        else:
                            answersTxt = {'words_result': [{'words': ''}]}
                    # print('题干：', questionTxt)
                    # print('答案：', answersTxt)
                    # question = txt["words_result"]
                    # answersList = answers["words_result"]
                    # num = int(txt["words_result_num"])
                    break
                except Exception as e:
                    print(e)

            x, y = new_search(questionTxt, answersTxt, text, answer_text, auto,
                              check)
            if x:
                left, top, right, bottom = win32gui.GetWindowRect(sajj_handle)
                # 输出坐标信息
                # print('窗口左上角坐标：({}, {})'.format(left, top))
                # print('窗口右下角坐标：({}, {})'.format(right, bottom))
                print(f'答案相对坐标：{x}，{y}')
                # 鼠标目标坐标
                targetX = left + x
                targetY = top + y + offset
                #打开自动点击
                if autoclick:
                    mouse_x, mouse_y = pyautogui.position()
                    pyautogui.moveTo(targetX, targetY)
                    print(mouse_x, mouse_y)
                    pyautogui.click()
                    pyautogui.moveTo(mouse_x, mouse_y)
                #打开标记
                elif mark:
                    for _ in range(10):
                        # 画一个小白框
                        dcObj.Rectangle(
                            (targetX, targetY, targetX + 10, targetY + 10))
                        win32gui.InvalidateRect(hwnd_from_point, monitor,
                                                True)  # 刷新显示器
        else:
            print("挑战答题")


if not os.path.exists(f'{local_path}{os.sep}baidu.json'):
    with open(f'{local_path}{os.sep}baidu.json', 'w') as f:
        f.write("""{
    "APP_ID": "",
    "API_KEY": "",
    "SECRET_KEY": ""
}""")
root = tkinter.Tk()
changeVar = tkinter.BooleanVar()
checkTextVar = tkinter.StringVar()
changeVar.set(True)
checkTextVar.set("每日答题")
sw = root.winfo_screenwidth()  #得到屏幕宽度
sh = root.winfo_screenheight()  #得到屏幕高度
offset = sh // 5
root.title("水安将军辅助")
if sajj_handle:

    def checkClick():
        if changeVar.get():
            checkTextVar.set("每日答题")
        else:
            checkTextVar.set("挑战答题")

    root.title("按空格获取答案")
    left1, top1, right1, bottom1 = win32gui.GetWindowRect(sajj_handle)
    # root = tkinter.Tk()
    root.geometry(f"320x800+{left1+(right1-left1)}+{top1}")
    check = tkinter.Checkbutton(root,
                                variable=changeVar,
                                textvariable=checkTextVar,
                                command=checkClick)
    check.pack()
    text = tkinter.Text(root, width=100, height=5)
    text.pack()
    answer_text = tkinter.Text(root, width=100, font=("黑体", 30), fg="red")
    answer_text.pack()
    question = ""
    th = threading.Thread(target=screen_thread)
    # th.setDaemon(True)
    try:
        th.daemon = True
    except:
        th.setDaemon(True)
    th.start()
    root.mainloop()
else:
    print("打开“水安将军”小程序才能使用")
    ww = 240
    wh = 120
    root.geometry("%dx%d+%d+%d" % (ww, wh, sw // 3, sh // 3))

    def close_window():
        root.destroy()

    label = tkinter.Label(root, text="请打开“水安将军”小程序后运行")
    label.pack(pady=10)

    button = tkinter.Button(root, text="关闭窗口", command=close_window)
    button.pack(pady=30)
    root.mainloop()